package me.sdevil507.supports.shiro.redis;

import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.connection.RedisStandaloneConfiguration;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.connection.lettuce.LettucePoolingClientConfiguration;
import org.springframework.stereotype.Component;

/**
 * 自定义redis提供者
 * <p>
 * 该提供者主要提供RedisConnectionFactory
 * 可以复用应用中的,也可以自己创建指定额外的数据源
 *
 * @author sdevil507
 * created on 2023/4/11
 */
@Component
public class CustomShiroRedisProvider implements ShiroRedisProvider {

    @Autowired
    private ShiroRedisProperties redisProperties;

    @Override
    public RedisConnectionFactory initConnectionFactory() {
        // 我此处使用的是Lettuce连接池,也可以替换为jedis配置
        // 创建单节点模式配置,并设置相关参数(集群模式需要修改配置)
        RedisStandaloneConfiguration redisConfiguration = new RedisStandaloneConfiguration(redisProperties.getHost(), redisProperties.getPort());
        redisConfiguration.setDatabase(redisProperties.getDatabase());
        redisConfiguration.setPassword(redisProperties.getPassword());
        // Lettuce连接池相关配置
        GenericObjectPoolConfig<Object> poolConfig = new GenericObjectPoolConfig<>();
        poolConfig.setMaxTotal(redisProperties.getLettuce().getPool().getMaxActive());
        poolConfig.setMaxWait(redisProperties.getLettuce().getPool().getMaxWait());
        poolConfig.setMaxIdle(redisProperties.getLettuce().getPool().getMaxIdle());
        poolConfig.setMinIdle(redisProperties.getLettuce().getPool().getMinIdle());
        LettucePoolingClientConfiguration.LettucePoolingClientConfigurationBuilder builder = LettucePoolingClientConfiguration.builder();
        LettucePoolingClientConfiguration lettucePoolingClientConfiguration = builder.build();
        builder.poolConfig(poolConfig);
        LettuceConnectionFactory connectionFactory = new LettuceConnectionFactory(redisConfiguration, lettucePoolingClientConfiguration);
        connectionFactory.afterPropertiesSet();
        return connectionFactory;
    }
}
